package com.spider.service;

import com.alibaba.fastjson.JSONObject;
import com.spider.constant.JiLiUrl;
import com.spider.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.LinkedHashMap;

@Service
public class JiliUtilServiceImpl implements JiliUtilService{
    @Autowired
    RestTemplate restTemplate;

    @Override
    @CachePut(value = "jiliToken")
    public String createToken(){
        //拼接参数
        String url= JiLiUrl.PRODUCT_URL+JiLiUrl.TOKEN_URL;
        JSONObject jb=new JSONObject(new LinkedHashMap());
        jb.put("client_id",JiLiUrl.clientId);
        jb.put("client_secret",JiLiUrl.clientSecret);
        System.out.println(jb);
        ResponseEntity<String> result=restTemplate.postForEntity(url,jb,String.class);
        String res= StringUtil.unicodeDecode(result.toString());
        System.out.println(res);
        res=res.substring(5,res.length()-1).split("}}")[0]+"}}";
        System.out.println(res);
        JSONObject resObject=JSONObject.parseObject(res);
        JSONObject content= (JSONObject) resObject.get("content");
        res= (String) content.get("access_token");
        return res;
    }

    @Override
    @Cacheable(value = "jiliToken")
    public String getToken() {
        return null;
    }
}
